package project.base.common.util

import com.alibaba.excel.EasyExcel
import javax.servlet.http.HttpServletResponse

/**
 * easyExcel工具类
 * @author 三味
 * @since 2022/3/4 16:03
 */
open class ExcelUtil {

    /**
     * @Author: 三味
     * @CreateTime:2021/12/2 19:10
     * @Description: 导出Excel（单页）
     * @param response  http响应对象
     * @param list  打印数据集合
     * @param fileName  文件名
     * @param className 打印数据的实体类
     * @param excludeColumnFiledNames   自定义排除的列（没有传null）
     */
    open fun <T : Any> export2Excel(response: HttpServletResponse,
                                    list: List<T>,
                                    fileName: String,
                                    className: Class<T>,
                                    excludeColumnFiledNames: MutableSet<String>?
    ){
        // 设置格式
        response.contentType = "application/vnd.ms-excel"
        response.characterEncoding = "utf-8"

        // 需要设置Access-Control-Expose-Headers，否则即使network中存在，js也无法拿到Content-Disposition
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")
        response.setHeader("Content-Disposition", "attachment;filename=$fileName")

        EasyExcel.write(response.outputStream, className)
                .excludeColumnFiledNames(excludeColumnFiledNames)
                .sheet("sheet1")    // 单页
                .doWrite(list)
    }

    /**
     * @Author: 三味
     * @CreateTime:2021/12/2 19:52
     * @Description: 导出Excel（单页）
     */
    open fun <T : Any> export2Excel(response: HttpServletResponse,
                                    list: List<T>,
                                    fileName: String,
                                    className: Class<T>
    ){
        export2Excel(response, list, fileName, className, null)
    }
}
